package com.snail.snailvr.utils;

import android.content.Context;
import android.util.Log;

import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.model.DownloadInfoChangeEvent;
import com.snail.snailvr.model.TaskInfo;
import com.snail.snailvr.network.providers.downloads.DownloadManager;
import com.snail.snailvr.network.providers.downloads.DownloadHelper;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;


/**
 * 在非强制更新下，如果是 wifi，启动一个service 静默下载安装包后 提示更新
 * Created by TAJ_C on 2014/12/15.
 */
public class SilenceUpdateServicesUtil {


    private Context mContext;
    private static SilenceUpdateServicesUtil instance;

    public static SilenceUpdateServicesUtil getInstance(Context context) {
        if (instance == null) {
            instance = new SilenceUpdateServicesUtil(context);
        }
        return instance;
    }

    public SilenceUpdateServicesUtil(Context context) {
        this.mContext = context;
        init();
    }

    @Subscribe
    public void onDownloadInfoChange(DownloadInfoChangeEvent event) {
        ArrayList<TaskInfo> taskInfos = event.getTaskInfos();
        if (taskInfos != null) {
            for (TaskInfo taskInfo : taskInfos) {
                String uri = taskInfo.getVideoLocalUri();
                if (uri!=null&&uri.endsWith(Constant.APK)) {
                    changeState(taskInfo);
                    break;
                }
            }
        }
    }

    public void init() {
        BusProvider.getInstance().register(this);
    }


    /**
     * 根据状态 处理
     *
     * @param taskInfo
     */
    private void changeState(TaskInfo taskInfo) {
        switch (taskInfo.getDownloadState()) {
            case DownloadManager.STATUS_SUCCESSFUL:        // 下载完成
                ApkInstaller.installApk(taskInfo.getVideoLocalUri());
                onDestroy();
                break;

            case DownloadManager.STATUS_FAILED:    // 下载失败 则删除任务等待下一次
                DownloadManager manager = DownloadHelper.getDownloadManager();
                if (manager.remove(taskInfo.getTaskId()) == 1) {
                    // delete apk
                    PackageInfoUtil.deleteApkFromDiskByUri(taskInfo.getVideoLocalUri());
                }
                break;
            case DownloadManager.STATUS_PAUSED:     // 下载暂停

                Log.d("Test",taskInfo.getReason() + "");
                DownloadHelper.resumeDownload(mContext, taskInfo.getTaskId());
                break;

            default:
                break;
        }
    }


    public void onDestroy() {
        BusProvider.getInstance().unregister(this);
        instance = null;
    }


}
